<?php
/**
 * 内容管理类
 */
class content
{
    private $table;
    private $table_rel;
    private $db;
    public $pages;
    public $modulename;

    public function __construct($modulename='category')
    {
        global $db;
        $this->db = $db;
        $this->table = DB_PRE.'content';
        $this->table_rel = DB_PRE . 'content_rel';
        $this->modulename = empty($modulename) ? 'category' : $modulename;
    }

    /**
     * 查询新闻列表
     * @author menghao
     * @param <array> $condition
     * @param <int> $page
     * @param <int> $pagesize
     * @return <array>
     */
    public function listinfo($condition, $page=1, $pagesize=20)
    {
        $page = max(intval($page), 1);
        $offset = ($page-1) * $pagesize;

        $where = 'where module=?';
        if(!empty($condition['catid']))
        {
            $where .= " and (catid=? or exists (select * from $this->table_rel where catid=? and module=? and contentid={$this->table}.id))";
        }
        if(isset($condition['status']) && is_numeric($condition['status']))
        {
            $where .= " and status=?";
        }
        elseif(isset($condition['status']) && strpos($condition['status'], ','))
        {
            $where .= " and status in({$condition['status']})";
        }
        else
        {
            $where .= " and status <>".STATUS_DEL .' and status <> ' . STATUS_RECYCLE;
        }
        if(isset($condition['author']))
        {
            $where .= " and username =? ";
        }
        if(!empty($condition['type']) && !empty($condition['searchtext']))
        {
            switch($condition['type'])
            {
                case 1 : //按标题
                    $where .= " and title like ?";
                    break;
                case 2 : //按用户发表
                    $where .= " and username=?";
                    break;
                case 3 : //按ID
                    $where .= " and id=?";
                    break;
            }
        }
        if(!empty($condition['starttime']))
        {
            $where .= " and addtime>=?";
        }
        if(!empty($condition['endtime']))
        {
            $where .= " and addtime<=?";
        }
        $this->db->prepare("select * from $this->table $where order by listorder desc, addtime desc limit $offset,$pagesize");
        $this->db->set_string($this->modulename);
        if(!empty($condition['catid']))
        {
            $this->db->set_string($condition['catid']);
            $this->db->set_string($condition['catid']);
            $this->db->set_string($this->modulename);
        }
        if(isset($condition['status']) && is_numeric($condition['status']))
        {
            $this->db->set_int($condition['status']);
        }
        if(isset($condition['author']))
        {
            $this->db->set_string($condition['author']);
        }
        if(!empty($condition['type']) && !empty($condition['searchtext']))
        {
            if($condition['type']==1)
            {
                $condition['searchtext'] = "%{$condition['searchtext']}%";
            }
            $this->db->set_string($condition['searchtext']);
        }
        if(!empty($condition['starttime']))
        {
            $this->db->set_int(strtotime($condition['starttime']));
        }
        if(!empty($condition['endtime']))
        {
            $this->db->set_int(strtotime($condition['endtime']));
        }

        $data = $this->db->execute();

        $this->db->prepare("select count(*) count from $this->table $where");
        $this->db->set_string($this->modulename);
        if(!empty($condition['catid']))
        {
            $this->db->set_string($condition['catid']);
            $this->db->set_string($condition['catid']);
            $this->db->set_string($this->modulename);
        }
        if(isset($condition['status']) && is_numeric($condition['status']))
        {
            $this->db->set_int($condition['status']);
        }
        if(isset($condition['author']))
        {
            $this->db->set_string($condition['author']);
        }
        if(!empty($condition['type']) && !empty($condition['searchtext']))
        {
            if($condition['type']==1)
            {
                $condition['searchtext'] = "%{$condition['searchtext']}%";
            }
            $this->db->set_string($condition['searchtext']);
        }
        if(!empty($condition['starttime']))
        {
            $this->db->set_int(strtotime($condition['starttime']));
        }
        if(!empty($condition['endtime']))
        {
            $this->db->set_int(strtotime($condition['endtime']));
        }
        $data2 = $this->db->execute(true);
        $count = $data2['count'];
        $this->pages = pages($count, $page, $pagesize);
        return $data;
    }

    /**
     * 生成内容模型表单
     * @author menghao
     * @param <int> $modelid
     * @param <array> $data
     * @return <array>
     */
    public function create_form($modelid, $data='')
    {
        $model = cache_read('model_'.$modelid);
        $fields = $model['fields'];
        $form = array();
        if(is_array($fields))
        {
            foreach($fields as $key=>$f)
            {
//                if($f['showedit']!=1) continue;
                include_once dirname(__FILE__)."/fields/{$f['formtype']}.class.php";
                $field_class = 'field_'.$f['formtype'];
                $field_obj = new $field_class($fields[$key]);
                $data[$key] = isset($data[$key]) ? $data[$key] : '';
                $form[$key]['input'] = $field_obj->create_form($data[$key]);
                $form[$key]['tips'] = $field_obj->creat_tip();
                $form[$key]['name'] = $f['name'];
                $form[$key]['showedit'] = $f['showedit'];
            }
        }
        return $form;
    }

    /**
     * 添加内容
     * @author menghao
     * @param <array> $data
     * @return <int> contentid
     */
    public function add($data)
    {
        $insert_data = $this->get_content($data);
        if(empty($insert_data))
        {
            return false;
        }
        $this->db->insert($this->table, $insert_data['data']);
        $insert_data['data']['contentid'] = $this->db->uuid();
        $this->db->insert($insert_data['customtable'], $insert_data['data']);
        return $insert_data['data']['contentid'];
    }

    /**
     * 校验并返回所添加内容
     * @author menghao
     * @global <array> $CATEGORY
     * @param <array> $data
     * @return <mixed>
     */
    public function get_content($data)
    {
        global $CATEGORY,$response;
        $catid = @get_null($data['catid'], '');
        $modelid = @get_null($data['modelid'], $CATEGORY[$catid]['modelid']);
        $model = cache_read('model_'.$modelid);
        $fields = $model['fields'];

        $insert_data = array('customtable'=>DB_PRE.'c_'.$model['tablename']);

        if(is_array($fields))
        {
            foreach($fields as $key=>$f)
            {
                if(!isset($data[$key])) continue;
                include_once dirname(__FILE__)."/fields/{$f['formtype']}.class.php";
                $field_class = 'field_'.$f['formtype'];
                $field_obj = new $field_class($fields[$key]);
                $data[$key] = $field_obj->get_data($data[$key]);
                if(!$field_obj->check_data($data[$key]))
                {
                    $this->error = $field_obj->error;
                }
            }
        }
        if(!empty($this->error))
        {
            $response->real_execute();
        }
        $data['modelid'] = $modelid;
        $data['updatetime'] = TIME;
        $data['addtime'] = is_numeric($data['addtime']) ? $data['addtime'] : strtotime($data['addtime']);
        $insert_data['data'] = $data;
        return $insert_data;
    }

    /**
     * 更改文章状态
     * @author menghao
     * @param <int> $id
     * @param <int> $status
     * @return <boolean>
     */
    function status($id, $status)
    {
        $status = intval($status);
        $this->db->prepare("update $this->table set status=? where id=?");
        $this->db->set_int($status);
        $this->db->set_string($id);
        return $this->db->execute();
    }

    /**
     * 批量删除文章
     * @author menghao
     * @param <array> $info
     * @return <boolean>
     */
    function delete_all($info,$siteid)
    {
    	global $hook_obj;
        if(is_array($info))
        {
            foreach($info as $id)
            {
                if(!$this->status($id, STATUS_RECYCLE))
                {
                    return false;
                }
                $hook_obj->op_hook('after_del_content', $siteid, array('contentid'=>$id));
            }
        }
        return true;
    }

    /**
     * 内容排序
     * @author menghao
     * @param <array> $listorder
     * @return <boolean>
     */
    function listorder($listorder)
    {
        if(is_array($listorder))
        {
            foreach($listorder as $i=>$v)
            {
                $v = intval($v);
                $this->db->query("update $this->table set listorder=$v where id='$i'");
            }
        }
        return true;
    }

    /**
     * 获取一篇文章的全部内容
     * @author menghao
     * @param <int> $id
     * @return <array>
     */
    function get_one($id)
    {
        $system = $this->db->get_one($this->table, $id);
        if(empty($system)) return false;

        $model = cache_read('model_'.$system['modelid']);
        $customtable = DB_PRE.'c_'.$model['tablename'];
        $custom = $this->db->get_one($customtable, $id, 'contentid');
        $custom = is_array($custom) ? $custom : array();
        return array_merge($system, $custom);
    }

    /**
     * 根据relid获取新闻内容，并将catid设置为相关栏目id
     * @author menghao
     * @param <type> $cid
     * @return <type>
     */
    public function get_by_rel($cid)
    {
        $sql = "select * from $this->table_rel where cid=? and status=?";
        $this->db->prepare($sql);
        $this->db->set_string($cid);
        $this->db->set_int(STATUS_NORMAL);
        $data = $this->db->execute(true);
        if(empty($data))
        {
            return false;
        }
        $content = $this->get_one($data['contentid']);
        if(empty($content))
        {
            return false;
        }
        $content['catid'] = $data['catid'];
        return $content;
    }

    /**
     * 修改内容
     * @author menghao
     * @param <int> $id
     * @param <array> $data
     * @return <boolean>
     */
    function edit($id, $data)
    {
        $insert_data = $this->get_content($data);
        if(empty($insert_data))
        {
            return false;
        }
        $this->db->simple_update($this->table, $insert_data['data'], array('id'=>$id));
        $this->db->simple_update($insert_data['customtable'], $insert_data['data'], array('contentid'=>$id));
        return true;
    }

    /**
     * 检查内容操作权限
     * @author menghao
     * @param <string> $catid
     * @param <string> $perms
     * @return <boolean>
     */
    function check_perms($catid, $perms)
    {
        global $current_user;
        if($current_user['usertype']==USER_TYPE_SUPER)
        {
            return true;
        }
        $view_list = get_user_resource_list($this->modulename);
        if(!isset($view_list[$catid]))
        {
            $view_list[$catid] = false;
            return false;
        }
        if(!empty($perms) && check_perms($perms, $view_list[$catid])===false)
        {
            return false;
        }
        return true;
    }

    /**
     * 彻底删除文章 $contentid如果是数组则批量删除
     * @author menghao
     * @param <mixed> $contentid
     * @return <boolean>
     */
    function delete($contentid)
    {
        if(is_array($contentid))
        {
            foreach($contentid as $id)
            {
                $this->delete($id);
            }
        }
        else
        {
            $content = $this->get_one($contentid);
            if(empty($content)) return false;
            $this->db->fake_delete($this->table, array('id'=>$contentid));
            $model = cache_read('model_'.$content['modelid']);
            if(!empty($model))
            {
                $customtable = DB_PRE.'c_'.$model['tablename'];
                $this->db->fake_delete($customtable, array('contentid'=>$contentid));
            }
        }
        return true;
    }

    /**
     * 清空回收站
     * @author menghao
     * @return <boolean>
     */
    function clear_all($catid)
    {
//        set_time_limit(999999999);
        $this->db->prepare("select id from $this->table where status=? and module=? and catid=?");
        $this->db->set_int(STATUS_RECYCLE);
        $this->db->set_string($this->modulename);
        $this->db->set_string($catid);
        $data = $this->db->execute();
        if(is_array($data))
        {
            foreach($data as $r)
            {
                $this->delete($r['id']);
            }
        }
        return true;
    }

    /**
     * 还原删除的文章 $contentid如果是数组则批量还原
     * @author menghao
     * @param <mixed> $contentid
     * @return <booean>
     */
    function recover($contentid)
    {
        if(is_array($contentid))
        {
            foreach($contentid as $id)
            {
                $this->recover($id);
            }
        }
        else
        {
            $this->db->prepare("update $this->table set status=? where id =?");
            $this->db->set_int(STATUS_RECOVER);
            $this->db->set_string($contentid);
            if(!$this->db->execute())
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 还原所有删除的文章
     * @author menghao
     * @return <boolean>
     */
    function recover_all($catid)
    {
        $this->db->prepare("update $this->table set status=? where status =? and module=? and catid=?");
        $this->db->set_int(STATUS_RECOVER);
        $this->db->set_int(STATUS_RECYCLE);
        $this->db->set_string($this->modulename);
        $this->db->set_string($catid);
        return $this->db->execute();
    }


    /**
     * 发布新闻时选择主栏目
     * @global <object> $DB
     * @global <array> $CATEGORY
     * @param <string> $name
     * @param <string> $id
     * @param <string> $value
     * @param <string> $default
     * @param <string> $extren
     * @return <string> select 控件
     */
    public function select_category($name, $id = '', $value='', $default='', $extren='', $modelid='')
    {
        global $db, $CATEGORY;
        $CURRENT_SITEID = get_current_site();
        if(!check_perms('post_to_other_cate'))
        {
            if(isset($CATEGORY[$value]))
            {
                $catname = $CATEGORY[$value]['catname'];
                return "$catname <input type='hidden' name='catid' value='$value' />";
            }
            else
            {
                return '';
            }
        }
        include_once APP_ROOT . 'include/tree.class.php';

        if(empty($id))
        {
            $id = $name;
        }
        $org_modelid = @get_null($CATEGORY[$value]['modelid'], $modelid);
        $catlist = array();
        foreach($CATEGORY as $catid => $cat)
        {
            if($cat['modelid'] !== $org_modelid || $cat['siteid'] != $CURRENT_SITEID)
            {
                continue;
            }
            $catlist[$catid] = $cat;
        }
        $tree = new tree($catlist);
        return "<select name='$name' id='$id' $extren>" . $tree->get_tree('', "<option value='\$catid' \$selected>\$spacer\$catname</option>", $value) . '</select>';
    }

    /**
     * 发布到其他栏目时选择栏目
     * @global  $CATEGORY
     * @param <string> $catid
     * @param <string> $name
     * @param <string> $value
     * @param <string> $modelid
     * @return string
     */
    public function get_category_tree($catid, $name, $value = array(), $modelid = '')
    {
        global $CATEGORY;
        $tree = "<ul>";
        $subcat = $this->get_sub_cat($catid);
        if(is_array($subcat))
        {
            foreach($subcat as $cid => $sub)
            {
                if(!$this->check_perms($cid, 'CON002'))
                {
                    continue;
                }
                if(!$CATEGORY[$cid]['showinother'])
                {
                    continue;
                }
                $subname = $CATEGORY[$cid]['catname'];
                $subtree = $this->get_category_tree($cid, $name, $value, $modelid);
                $checked = in_array($cid, $value) ? 'checked' : '';
                $disabled = $CATEGORY[$cid]['modelid'] == $modelid ? '' : "disabled='true'";
                $tree .= "<li><input type='checkbox' $checked $disabled name='{$name}[]' value='$cid'>{$subname}{$subtree}</li>";
            }
        }
        $tree .= "</ul>";
        return $tree;
    }

    /**
     * 获得某一栏目的所有子栏目
     * @global  $CATEGORY
     * @param <string> $catid
     * @return <string>
     */
    private function get_sub_cat($catid)
    {
        global $CATEGORY;
        $sub_cat = array();
        foreach ($CATEGORY as $cat)
        {
            if($cat['parentid'] == $catid)
            {
                $sub_cat[$cat['catid']] = $cat;
            }
        }
        return $sub_cat;
    }

    /**
     * 添加某一新闻的关联栏目
     * @param <string> $contentid
     * @param <string> $relcat
     * @return <boolean>
     */
    public function add_rel($contentid, $relcat)
    {
        if(!is_array($relcat))
        {
            return false;
        }
//        require_once 'html.class.php';
//        $html = new html();

        $content = $this->get_one($contentid);
//        $path = 'publish/'. date('Y/md/', $content['addtime']) . 'content_';

        $old_rels = $this->get_rels($contentid);
        $add_rels = array_diff($relcat, $old_rels);
        $del_rels = array_diff($old_rels, $relcat);
        $this->del_rel($contentid, $del_rels);

        foreach($add_rels as $catid)
        {
            if(empty($catid)) continue;
            $this->db->insert($this->table_rel, array('contentid'=>$contentid, 'catid'=>$catid, 'module'=>$this->modulename));
            $cid = $this->db->uuid();
//            $html->show($cid,$catid,$contentid);
        }
//        $url = date('Y',TIME) . '/' . date('m', TIME) . date('d', TIME) . '/content/' . $cid . '.html';
        $this->db->query("update $this->table_rel set url = concat('content_',cid,'.html')");
        return true;
    }

    /**
     * 删除某一新闻的关联栏目
     * @param <string> $contentid
     * @return <boolean>
     */
    private function del_rel($contentid, $relcat)
    {
        if(!is_array($relcat) || empty($relcat))
        {
            return false;
        }
        $rels = implode("','", $relcat);
        $this->db->prepare("update $this->table_rel set status=? where contentid=? and module=? and catid in ('$rels')");
        $this->db->set_int(STATUS_DEL);
        $this->db->set_string($contentid);
        $this->db->set_string($this->modulename);
        return $this->db->execute();
    }

    public function get_cids($cid)
    {
        $this->db->prepare("select * from $this->table_rel where cid=?");
        $this->db->set_string($cid);
        $data = $this->db->execute(true);
        return $data;
    }

    /**
     * 获取某一新闻的关联栏目
     * @param <string> $contentid
     * @return <array>
     */
    public function get_rels($contentid)
    {
        $this->db->prepare("select catid from $this->table_rel where contentid=? and status=?");
        $this->db->set_string($contentid);
        $this->db->set_int(STATUS_NORMAL);
        $data = $this->db->execute();
        $catids = array();
        if(is_array($data))
        {
            foreach($data as $r)
            {
                $catids[] = $r['catid'];
            }
        }
        return $catids;
    }

    public function get_audit_status($catid,$workflowid='')
    {
        global $CATEGORY;
        include_once APP_ROOT.'admin/include/workflow.class.php';
        $workflow = new workflow();

//        $processid =
        $workflowid = empty($workflowid) ? $CATEGORY[$catid]['workflowid'] : $workflowid;
        $proc_list = $workflow->process_list($workflowid);
        $status_list = array();
        foreach($proc_list as $p)
        {
            $permcode = "process_{$p['id']}";
            if($this->check_perms($catid, $permcode))
            {
                $status_list[$p['rejectstatus']] = $p['rejectname'];
                $status_list[$p['passstatus']] = $p['passname'];
            }
        }
        return $status_list;
    }
}
?>
